<template>
  <div>
    <van-nav-bar title="个人中心" left-arrow @click-left="$router.back()" />
    <input type="file" ref="file" hidden @change="onFileChange" />
    <van-cell title="头像" is-link @click="$refs.file.click()">
      <van-image slot="default" fit="cover" round :src="userProfile.photo" />
    </van-cell>
    <van-cell
      title="昵称"
      :value="name"
      is-link
      @click="isShowEditName = true"
    ></van-cell>
    <van-cell
      title="性别"
      :value="userProfile.gender === 0 ? '男' : '女'"
      is-link
      @click="isShowEditGender = true"
    ></van-cell>
    <van-cell
      title="生日"
      :value="birthday || '未设置'"
      is-link
      @click="isShowEditBirthday = true"
    ></van-cell>

    <!-- 修改昵称弹窗 -->
    <van-popup
      v-model="isShowEditName"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <van-nav-bar
        title="设置昵称"
        left-text="取消"
        right-text="完成"
        @click-left="close"
        @click-right="sureEditName"
      />
      <van-field
        v-model="userProfile.name"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </van-popup>

    <!-- 修改性别弹窗 -->
    <van-popup
      v-model="isShowEditGender"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-picker
        title="性别"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="isShowEditGender = false"
      />
    </van-popup>

    <!-- 修改生日弹出层 -->
    <van-popup
      v-model="isShowEditBirthday"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="isShowEditBirthday = false"
        @confirm="sureEditBirthday"
      />
    </van-popup>

    <!-- 编辑头像弹出层 -->
    <van-popup
      class="photo"
      v-model="isShowEditAvatar"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="avatar" v-if="isShowEditAvatar">
        <img ref="img" :src="url" class="img" />
      </div>
      <van-nav-bar
        class="bottom"
        left-text="取消"
        right-text="确定"
        @click-left="isShowEditAvatar = false"
        @click-right="sureEditAvatar"
      />
    </van-popup>
  </div>
</template>

<script>
import { getUserProfile, updateUserProfile, updateUserPhoto } from '@/api/user'
import dayjs from 'dayjs'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  data () {
    return {
      userProfile: {},
      isShowEditName: false,
      name: '',
      isShowEditGender: false,
      columns: ['男', '女'],
      isShowEditBirthday: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(),
      currentDate: '',
      birthday: '',
      isShowEditAvatar: false,
      url: '',
      cropper: {}
    }
  },

  created () {
    this.loadUserProfile()
    this.currentDate = this.userProfile.birthday
  },
  updated () {
    if (this.isShowEditAvatar) {
      const image = this.$refs.img
      this.cropper = new Cropper(image, {
        dragMode: 'move',
        aspectRatio: 1,
        autoCropArea: 1,
        cropBoxMovable: false,
        cropBoxResizable: false,
        background: false,
        center: true
      })
    }
  },
  methods: {
    async loadUserProfile () {
      try {
        const res = await getUserProfile()
        this.userProfile = res.data.data
        this.name = this.userProfile.name
        this.birthday = this.userProfile.birthday
        this.currentDate = new Date(this.userProfile.birthday)
      } catch (error) {
        this.$toast('获取用户信息失败，请稍后再试！')
      }
    },
    async sureEditName () {
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })
      if (this.userProfile.name.trim().length === 0) {
        return this.$toast('昵称不能为空！')
      }
      try {
        await updateUserProfile({
          name: this.userProfile.name
        })
        this.name = this.userProfile.name
        this.isShowEditName = false
        this.$toast('修改成功!')
      } catch (error) {
        this.$toast('修改失败，请稍后再试！')
      }
    },
    close () {
      this.isShowEditName = false
      this.userProfile.name = this.name
    },
    async onConfirm (value) {
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })
      try {
        await updateUserProfile({
          gender: value === '男' ? 0 : 1
        })
        this.$toast('修改成功！')
        this.isShowEditGender = false
        this.userProfile.gender = value === '男' ? 0 : 1
      } catch (error) {
        this.$toast('修改失败，请稍后再试！')
      }
    },
    async sureEditBirthday (value) {
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })
      try {
        await updateUserProfile({
          birthday: dayjs(value).format('YYYY-MM-DD')
        })
        this.$toast('修改成功！')
        this.currentDate = value
        this.birthday = dayjs(value).format('YYYY-MM-DD')
        this.isShowEditBirthday = false
      } catch (error) {
        this.$toast('修改失败，请稍后再试！')
      }
    },
    onFileChange () {
      const file = this.$refs.file.files[0]
      const url = window.URL.createObjectURL(file)
      this.isShowEditAvatar = true
      this.url = url
      this.$refs.file.value = ''
    },
    sureEditAvatar () {
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })

      this.cropper.getCroppedCanvas().toBlob(async blob => {
        const formData = new FormData()
        formData.append('photo', blob)
        try {
          const res = await updateUserPhoto(formData)
          this.userProfile.photo = res.data.data.photo
          this.isShowEditAvatar = false
          this.$toast('修改头像成功！')
        } catch (error) {
          if (error.response && error.response.status === 507) {
            return this.$toast('图片太大，请换张小图稍后再试！')
          }
          this.$toast('修改失败，请稍后再试！')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
/deep/.van-nav-bar__arrow {
  color: #fff;
}
.van-image {
  width: 60px;
  height: 60px;
}
/deep/.van-nav-bar__text {
  color: #fff;
}
.van-popup {
  background-color: #f5f7f9;
}
.van-field {
  width: 94%;
  margin: 20px auto 0;
}
.img {
  display: block;
  max-width: 100%;
}
.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: unset !important;
}
.photo {
  height: 100%;
  background-color: #000;
}
.avatar {
  height: 100% !important;
}
</style>
